package com.rocksdata.mc.ui.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.TextView;
import com.ctz.commonframe.ui.BaseActivity;
import com.ctz.commonframe.ui.WebViewActivity;
import com.ctz.commonframe.ui.view.NoScrollViewPager;
import com.ctz.commonframe.ui.widget.ViewPagerFragmentAdapter;
import com.ctz.commonframe.utils.ApplicationUtil;
import com.ctz.commonframe.utils.FilePathUtil;
import com.ctz.commonframe.utils.Logger;
import com.ctz.commonframe.utils.PermissonUtil;
import com.rocksdata.mc.business.BusinessInterface;
import com.rocksdata.mc.business.BusinessManager;
import com.rocksdata.mc.R;
import com.rocksdata.mc.business.UserInfoManager;
import com.rocksdata.mc.business.VersionManager;
import com.rocksdata.mc.entity.VersionInfo;
import com.rocksdata.mc.http.HttpClient;
import com.rocksdata.mc.ui.fragment.AnnouncementFragment;
import com.rocksdata.mc.ui.fragment.HomePageFragment;
import com.rocksdata.mc.ui.fragment.MeFragment;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;
import java.io.File;
import java.util.ArrayList;
import java.util.List;


@ContentView(R.layout.activity_main)
public class MainActivity extends BaseActivity {
    private static final int REQUEST_CODE_INSTALL_APK = 30001;

    @ViewInject(R.id.tv_main_tab1)
    private TextView tab1;
    @ViewInject(R.id.tv_main_tab2)
    private TextView tab2;
    @ViewInject(R.id.tv_main_tab3)
    private TextView tab3;
    @ViewInject(R.id.tv_main_tab4)
    private TextView tab4;
    @ViewInject(R.id.tv_main_tab5)
    private TextView tab5;
    @ViewInject(R.id.vp_main)
    private NoScrollViewPager vpMain;
    private ProgressDialog pbDownloading;
    private AlertDialog.Builder reloginDialog;

    private List<TextView> tabList = new ArrayList<>();
    private List<Fragment> fragmentList = new ArrayList<>();
    private int currentFragmentIndex;
    private long mExitTime;
    private File apkFile;
    private PermissonUtil permissonUtil;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);

        permissonUtil = PermissonUtil.getInstance();
        permissonUtil.checkPermissions(this,
                new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA,
                        Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION},
                new PermissonUtil.OnPermissionResultListener() {
                    @Override
                    public void onPermissionsPassed() {
                        initView();
                    }

                    @Override
                    public void onPermissionsDenied() {
                        showToast("部分权限未被允许导致部分功能不能正常使用");
                        finish();
                    }
                }
        );
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        permissonUtil.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    private void initView() {
        tab1.setTag(0);
        tab2.setTag(1);
        tabList.add(tab1);
        tabList.add(tab2);
        fragmentList.add(new HomePageFragment());
        fragmentList.add(new AnnouncementFragment());
        tab4.setVisibility(View.GONE);
        tab5.setTag(2);
        tabList.add(tab5);
        fragmentList.add(new MeFragment());

        vpMain.setAdapter(new ViewPagerFragmentAdapter(getSupportFragmentManager(), fragmentList));
        vpMain.setOffscreenPageLimit(tabList.size());
        tab1.setSelected(true);
        vpMain.setCurrentItem(0);

        getVersionInfo();

        HttpClient.setOnAuthErrorListener(new HttpClient.OnAuthErrorListener() {
            @Override
            public void onAuthError(String msg) {
                buildReloginDialog();
            }
        });
    }

    private void buildReloginDialog () {
        if (reloginDialog == null) {
            reloginDialog = new AlertDialog.Builder(MainActivity.this);
            reloginDialog.setTitle("账户已失效，请重新登录");

            reloginDialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    exit();
                    BusinessManager.getAccountManager().logout();
                    Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }
            });
            reloginDialog.setCancelable(false);
        }

        reloginDialog.create().show();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }

    private void getVersionInfo() {
        BusinessManager.getVersionManager().getLatestVersionInfo(new BusinessInterface.OnBusinessResultListener() {
            @Override
            public void onBusinessResult(boolean isSuccess, Object object, String message) {
                if (isSuccess) {
                    VersionInfo info = (VersionInfo) object;
                    if (VersionManager.isLatestVersion(MainActivity.this, info)) {
                        showVersionDialog(info);
                    }
                }
            }
        });
    }

    private void showVersionDialog(final VersionInfo versionInfo) {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("检查版本");
        builder.setMessage("最新版本是" + versionInfo.getVersionName() + ",是否更新");
        builder.setNegativeButton("暂不更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        builder.setPositiveButton("马上更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                update(versionInfo);
            }
        });

        builder.create().show();
    }

    private void update(final VersionInfo versionInfo) {
        String saveDir = FilePathUtil.getDownloadDir(MainActivity.this);
        String apkName = versionInfo.getVersionURL().substring(versionInfo.getVersionURL().lastIndexOf("/") + 1);
        apkFile = new File(saveDir, apkName);
        if (apkFile.exists()) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//8.0
                update_Android_O();
                return;
            }

            ApplicationUtil.installApk(MainActivity.this, apkFile.getAbsolutePath());
        } else {
            if(pbDownloading == null) {
                pbDownloading = new ProgressDialog(MainActivity.this);
                pbDownloading.setCanceledOnTouchOutside(false);
                pbDownloading.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                pbDownloading.setProgressNumberFormat("%1d MB /%2d MB");
            }
            RequestParams requestParams = new RequestParams(versionInfo.getVersionURL());
            requestParams.setSaveFilePath(apkFile.getAbsolutePath());
            requestParams.setAutoRename(true);
            x.http().get(requestParams, new Callback.ProgressCallback<File>() {
                @Override
                public void onWaiting() {

                }

                @Override
                public void onStarted() {
                    pbDownloading.setTitle("正在下载");
                    pbDownloading.setMessage("请稍候...");
                    pbDownloading.show();
                }

                @Override
                public void onLoading(long total, long current, boolean isDownloading) {
                    pbDownloading.setMax((int) (total/(1024*1024)));
                    pbDownloading.setProgress((int) (current/(1024*1024)));
                }

                @Override
                public void onSuccess(File file) {
                    Logger.e("download success, path:" + file.getAbsolutePath());
                    apkFile = file;
                    pbDownloading.dismiss();
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//8.0
                        update_Android_O();
                        return;
                    }

                    ApplicationUtil.installApk(MainActivity.this, file.getAbsolutePath());
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    pbDownloading.dismiss();
                    showToast("下载失败");
                    Logger.e("下载失败，url:" + versionInfo.getVersionURL() + ", msg:" + ex.getLocalizedMessage());
                }

                @Override
                public void onCancelled(CancelledException cex) {
                    pbDownloading.dismiss();
                }

                @Override
                public void onFinished() {
                    pbDownloading.dismiss();
                }
            });
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void update_Android_O() {
        //来判断应用是否有权限安装apk
        boolean installAllowed = getPackageManager().canRequestPackageInstalls();
        //无权限 申请权限
        if (!installAllowed) {
            new AlertDialog.Builder(MainActivity.this)
                    .setTitle("提示")
                    .setMessage("安装应用需要打开安装未知来源应用权限，请去设置中开启权限")
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Uri packageUri = Uri.parse("package:" + getPackageName());
                            Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageUri);
                            startActivityForResult(intent, REQUEST_CODE_INSTALL_APK);
                        }
                    })
                    .show();
        } else {
            ApplicationUtil.installApk(MainActivity.this, apkFile.getAbsolutePath());
        }
    }

    @Event(value = { R.id.tv_main_tab1, R.id.tv_main_tab2, R.id.tv_main_tab3, R.id.tv_main_tab4, R.id.tv_main_tab5 })
    private void OnClick(View v) {
        if(UserInfoManager.isVisitor() && (v.getId() == R.id.tv_main_tab2 || v.getId() == R.id.tv_main_tab4) ){
            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
            intent.putExtra("showCancel", true);
            startActivity(intent);
            return;
        }
        for(TextView textView: tabList){
            if (textView == v){
                textView.setSelected(true);
                currentFragmentIndex = (Integer)textView.getTag();
                vpMain.setCurrentItem(currentFragmentIndex);
            }else{
                textView.setSelected(false);
            }
        }
    }

    public void setCurrentFragmentIndex(int index){
        for(TextView textView: tabList){
            if ((Integer)textView.getTag() == index){
                textView.setSelected(true);
                currentFragmentIndex = index;
                vpMain.setCurrentItem(currentFragmentIndex);
            }else{
                textView.setSelected(false);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_INSTALL_APK) {
            ApplicationUtil.installApk(MainActivity.this, apkFile.getAbsolutePath());
        } else {

            if (data != null) {
                boolean relogin = data.getBooleanExtra(WebViewActivity.EXTRA_KEY_RELOGIN, false);
                if (relogin) {
                    BusinessManager.getAccountManager().logout();
                    exit();
                    startActivity(new Intent(MainActivity.this, LoginActivity.class));
                    return;
                }
            }
            fragmentList.get(currentFragmentIndex).onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 1500) {
                showToast("再按一次退出");
                mExitTime = System.currentTimeMillis();
            } else {
                exit();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
